cmake_minimum_required(VERSION 3.15)

# 在 project() 之前手动包含工具链文件
# 检查 CMAKE_TOOLCHAIN_FILE 是否已定义且非空
if(DEFINED CMAKE_TOOLCHAIN_FILE AND CMAKE_TOOLCHAIN_FILE)
    message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}")
    if(EXISTS "${CMAKE_TOOLCHAIN_FILE}")
        include(${CMAKE_TOOLCHAIN_FILE})
        message(STATUS "Toolchain ${CMAKE_TOOLCHAIN_FILE} file included successfully")
    else()
        message(FATAL_ERROR "Toolchain file not found: ${CMAKE_TOOLCHAIN_FILE}")
    endif()
else()
    message(WARNING "CMAKE_TOOLCHAIN_FILE is not set or empty")
    # 可以在这里包含默认的工具链文件
    if(EXISTS "${CMAKE_SOURCE_DIR}/cmake/x86-toolchain.cmake")
        include(${CMAKE_SOURCE_DIR}/cmake/x86-toolchain.cmake)
        message(STATUS "Using default toolchain file")
    endif()
endif()

project(elf-load-test
        VERSION 1.0.0
        LANGUAGES C ASM
        )  

# 设置编译选项
set(COMMON_FLAGS 
    "-mcpu=cortex-a9 -mthumb-interwork -mfloat-abi=softfp -mfpu=neon -Wall -O0 -g -std=c99"
)

# 设置 C 编译器选项
set(CMAKE_C_FLAGS "${COMMON_FLAGS}")

# 设置汇编器选项（通过 gcc 传递给 as，-x assembler-with-cpp 支持预处理）
set(CMAKE_ASM_FLAGS "${COMMON_FLAGS} -x assembler-with-cpp")

set(TARGET_FILE "main.elf")
set(CMAKE_ASM_OUTPUT_EXTENSION ".o")

include_directories(inc)

set(LINKER_SCRIPT "link.ld")
get_filename_component(LINKER_SCRIPT_ABS "${LINKER_SCRIPT}" ABSOLUTE)

file(GLOB PROJECT_CSRC "src/*.c")
file(GLOB PROJECT_ASMSRC "src/*.S")  # 单独处理 .s 文件

message(STATUS "C sources: ${PROJECT_CSRC}")
message(STATUS "ASM sources: ${PROJECT_ASMSRC}")

add_executable(${TARGET_FILE} 
    ${PROJECT_CSRC}
    ${PROJECT_ASMSRC}
)

# 为汇编文件设置特定属性
set_source_files_properties(${PROJECT_ASMSRC} PROPERTIES
    LANGUAGE ASM
)

# 添加其他必要的链接选项
target_link_options(${TARGET_FILE} PUBLIC
    "-T${LINKER_SCRIPT_ABS}"
    "-Wl,-Map=${TARGET_FILE}.map" 
    "-specs=nosys.specs"
    "-Wl,--gc-sections"
    "-nostartfiles"
    "-nostdlib"
)


# 添加 ELF 到 BIN 的转换（在构建 main 后自动执行）
add_custom_command(TARGET ${TARGET_FILE} POST_BUILD
    COMMAND ${CMAKE_OBJCOPY} -O binary $<TARGET_FILE:${TARGET_FILE}> $<TARGET_FILE:${TARGET_FILE}>.bin
    COMMAND ${CMAKE_OBJCOPY} -O ihex $<TARGET_FILE:${TARGET_FILE}> $<TARGET_FILE:${TARGET_FILE}>.hex
    COMMAND ${CMAKE_OBJDUMP} -x -D $<TARGET_FILE:${TARGET_FILE}> > $<TARGET_FILE:${TARGET_FILE}>.s
    COMMAND ${CMAKE_SIZE} $<TARGET_FILE:${TARGET_FILE}>
    COMMENT "Converting ELF to binary and hex, and showing size"
)